package com.pphh.demo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.pphh.demo.exception.BlockException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 11/22/2018
 */
public class SentinelFlowControl extends FlowControl {

    @Override
    public void run() throws BlockException {
        Entry entry = null;
        try {
            entry = SphU.entry("HelloWorld");
            // execute the test task
            test();
        } catch (com.alibaba.csp.sentinel.slots.block.BlockException e) {
            // handle block logic
            throw new BlockException("task is blocked by sentinel.");
        } finally {
            // make sure that the exit() logic is called
            if (entry != null) {
                entry.exit();
            }
        }
    }

    public static void initSystemRule() {
        List<SystemRule> rules = new ArrayList<SystemRule>();
        SystemRule rule = new SystemRule();
        // max load is 3
        rule.setHighestSystemLoad(3.0);
        // max avg rt of all request is 200 ms
        rule.setAvgRt(200);
        // max total qps is 5
        rule.setQps(1);
        // max parallel working thread is 5
        rule.setMaxThread(1);
        rules.add(rule);
        SystemRuleManager.loadRules(Collections.singletonList(rule));
    }

}
